/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gidoo.xmldb.stored;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;

/**
 * Holds all needed stored procedures
 * @author thomas
 */
public class Predecessors
{

  public static ResultSet predec(long elementID) throws SQLException
  {
    
    Connection con = DriverManager.getConnection("jdbc:default:connection");
    PreparedStatement psParent = con.prepareCall(
      "select idparent from children where idchild=?");

    LinkedList<Long> prePath = new LinkedList<Long>();
    long currentID = elementID;

    while(currentID != -1)
    {
      psParent.setLong(1, currentID);
      currentID = -1;
      ResultSet rsParent = psParent.executeQuery();
      if(rsParent.next())
      {
        currentID = rsParent.getLong(1);
        prePath.add(currentID);
      }
    }

    // construct ResultSet from the parent list
    long[] asArray = new long[prePath.size()];
    int i = 0;
    for(Long l : prePath)
    {
      if(i < asArray.length)
      {
        asArray[i] = l;
      }
      i++;
    }
    return new LongArrayResultSet(asArray, "id", "leveldist");

  }  

  public static long predecByName(long elementID, String nameToSearchFor) throws SQLException
  {
    Connection con = DriverManager.getConnection("jdbc:default:connection");
    
    PreparedStatement psParent = con.prepareCall(
      "select idparent from children where idchild=?");
    PreparedStatement psName = con.prepareCall(
      "select name from elements where id=?");
    
    long currentID = elementID;

    while(currentID != -1)
    {
      psParent.setLong(1, currentID);
      currentID = -1;
      ResultSet rsParent = psParent.executeQuery();
      if(rsParent.next())
      {
        currentID = rsParent.getLong(1);
        psName.setLong(1, currentID);
        ResultSet rsName = psName.executeQuery();
        if(rsName.next())
        {
          String currentName = rsName.getString(1);
          if(nameToSearchFor.equals(currentName))
          {
            return currentID;
          }
        }
      }
    }
    
    return -1;
    
  }
  
}

